package com.bjsxt.controller;

import cn.hutool.core.lang.Snowflake;
import com.bjsxt.domain.Market;
import com.bjsxt.domain.UserFavoriteMarket;
import com.bjsxt.dto.R;
import com.bjsxt.service.MarketService;
import com.bjsxt.service.UserFavoriteMarketService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * @Description:
 * @ClassName: UserFavoriteMarketController
 * @Author: chenyu
 * @Date: 2025/3/20 9:35
 */
@RestController
@RequestMapping("/userFavorites")
@Api(tags = "用户市场收藏")
public class UserFavoriteMarketController {
    @Autowired
    private UserFavoriteMarketService userFavoriteMarketService;

    @Autowired
    private MarketService marketService;

    @Autowired
    private Snowflake snowflake;

    @PostMapping("/addFavorite")
    @ApiOperation(value = "用户收藏某个市场")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "market", value = "market的交易对和类型")
    )
    public R addFavorite(@RequestBody Market market) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        UserFavoriteMarket userFavoriteMarket = new UserFavoriteMarket();
        @NotNull String symbol = market.getSymbol();
        Market marketDb = marketService.getMarketBySymbol(symbol);
        userFavoriteMarket.setId(snowflake.nextId());
        userFavoriteMarket.setUserId(userId);
        userFavoriteMarket.setMarketId(marketDb.getId());
        userFavoriteMarket.setType(market.getType().intValue());
        boolean save = userFavoriteMarketService.save(userFavoriteMarket);
        if (save)
            return R.ok("收藏成功");
        return R.fail("收藏失败");
    }

    @DeleteMapping("/{symbol}")
    @ApiOperation(value = "用户取消收藏某个市场")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "symbol", value = "交易对")
    )
    public R delFavorite(@PathVariable("symbol") String symbol) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        Market marketDb = marketService.getMarketBySymbol(symbol);
        boolean isOk = userFavoriteMarketService.delUserFavoriteMarket(userId, marketDb);
        if (isOk)
            return R.ok("取消收藏成功");
        return R.fail("取消收藏失败");
    }
}
